/**
 * 费用申请模块业务入口
 */
import './presetVar'
import React, {Component} from 'react';
import {createPage, base, high, pageTo} from 'nc-lightapp-front';
import {tableButtonClick,pageButtonClick, afterEvent,onRowDoubleClick,refreshButtonClick} from './events';
import initTemplate,{routeChange} from './initTemplate';
import {getAfterEventParams} from 'ssccommon/utils/formulaUtils'
import {EditTable} from 'ssccommon/components/table';
import pubMessage from 'ssccommon/utils/pubMessage';
import getPageData from 'ssccommon/utils/getPageData';
import LinkQueryJkbxModel from 'ssccommon/linkquery/LinkQueryJkbxModel';
import Inspection from 'epmp/exports/components/Inspection';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import NCUploader from 'uap/common/components/NCUploader';
import attachments from 'uap/common/components/getAttachmentInfo';
import ApprovalTrans from 'uap/common/components/approvalTrans';
import LinkChangeHistoryModel from '../link-change/LinkChange';

const { getAttachments, getAttachmentsInfo } = attachments;
const { NCModal } = base;
import {
    BillStyle,
    BillHead,
    BillBody,
    Form,
    CardTableGroup,
    ButtonGroup,
    MultiButtonGroup
} from 'ssccommon/components/bill';

import {
    ProfileStyle,
    ProfileBody
} from 'ssccommon/components/profile';

import './index.less';

const pageButton = window.presetVar.pageButton;
window.assingUsers=[];
window.sureAssign = false;//确定指派
window.assignBillId = '';//有指派的情况下，第一次点保存提交实际保存成功的单据pk

class FYSQBill extends Component {

    constructor(props) {
        if (NODE_ENV == 'development') {
            window.NODE_ENV = 'development';
        }
        super();
        this.state = {
            btn: [presetVar.body.body1 + presetVar.areaBtnAction.del, presetVar.body.body1 + presetVar.areaBtnAction.edit],
            showModal: false,
            showUploader: false,
            target: null,
            billId : '',
            sourceData: null,
            showLinkBudget: false,
            ShowApproveDetail: false,
            billtype: '',
            compositedata : '',
            compositedisplay : '',
            Title : '',
            linkData:'',
            uploaderBtnDisable: false, //附件上传按钮可用状态
            showLinkQueryChangeHistory: false,
            linkChangeHisData: ''
        }
        this.close = this.close.bind(this);
        this.pubMessage = new pubMessage(props);
        this.getPageData = new getPageData(props);
        props.custom_this = this;
        initTemplate.call(this, props);

        // TOP NCCLOUD-61317 增加公式编辑后联动 chengwebc ADD
        props.setRelationAfterEventCallBack && props.setRelationAfterEventCallBack((props, changedField, changedArea, oldCard, newCard, index, rowId)=>{
            let params = getAfterEventParams(props, changedField, changedArea, oldCard, newCard, index, rowId);
            params.map((one)=>{
                afterEvent.call(this, props, one.moduleId, one.key, one.value, one.changedrows, one.index)
            })
        });

        props.use.form('head');
    }


    componentWillMount() {
           window.onbeforeunload = () => {
                let status = this.props.getUrlParam("status");
                if (status == 'edit'||status == 'add') return
           }
    }

    componentDidMount() {
      this.props.setHashChangeCallback(() => {
            routeChange.call(this, this.props);
      })
    }

    close() {
        this.setState({ showModal: false });
    }
    cancel(){
        this.setState({
            showLinkBudget: false
        })
    }
    affirm(info){
        this.setState({
            showLinkBudget: false
        })
    }
    openApprove = () => {
        this.setState({
            ShowApproveDetail: true
        })
    }

    closeApprove = () => {
        this.setState({
            ShowApproveDetail: false
        })
    }

    getAssginUser = (value) => {
        window.assingUsers = value;
        window.sureAssign = true;
        let props = this.props;
        if(props.getUrlParam('status') === 'browse'){
            pageButtonClick.call(this)[pageButton.billSubmit]();
        }else{
            pageButtonClick.call(this)[pageButton.billSaveSubmit]();
        }
        window.assignBillId = '';
    }

    turnOff(){
        this.setState({
            compositedisplay:false
        }) ;
        window.sureAssign = false;
        window.assingUsers = [];
        let id = this.props.getUrlParam('id') ? this.props.getUrlParam('id') : this.state.billId;
        if(id!=null && id.length>0){
     
        }
        let props = this.props;
        let billid = window.assignBillId;
        if(!billid){
            billid = props.form.getFormItemsValue('head', 'pk_mtapp_bill').value;
        }
        pageTo.specialLinkTo('/erm/erbudgetmg/erbudgetmg/card/index.html',{scene:props.getUrlParam('scene'),status:'browse',id:billid,ts:new Date().getTime()});
        routeChange.call(this, this.props)
    }

    onBeforeEvent(props, moduleId, key, value,  index, record,status){
        window.presetVar.bodyChangeValuesAll = record;
        return true;
    }

    onHideUploader = () => {
        this.setState({
            showUploader: false,
        });
        let id = this.props.getUrlParam('id') ? this.props.getUrlParam('id') : this.state.billId;
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId        
        getAttachments(id).then(lists => {
            this.props.button.setButtonTitle('fileManager', multiLang&&multiLang.get('201102SQFY-0031')/**'附件'**/ + ' ' + lists + ' ');
        })
    }

    renderErrorCenterState () {
        const { props } = this
        const { socket } = props;
        const status = props.form.getFormItemsValue('head', 'saga_status')
        if (!status || status.value !== '1') return null;
        
        this.props.button.toggleErrorStatus('head',{
            isError: true
        })

        const param = {
            headBtnAreaCode: 'head',
            formAreaCode: 'head',
            billtype: props.form.getFormItemsValue('head', 'saga_status').value,
            billpkname: 'pk_mtapp_bill',
            dataSource: 'erm.erbudgetmg.erbudetmg.card'
        }
        return props.socket.connectMesg(param)
    }

    render() {
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        let btnModalConfig = {
            [pageButton.pageDel] : {
                // "2011-0004": "删除",
                // "2011-0005": "确认删除该单据吗？"
                title: multiLang && multiLang.get('2011-0004'),
                content: multiLang && multiLang.get('2011-0005'),
            },
            [pageButton.billInvalid]: {
                // "2011-0009": "作废",
                // "2011-0010": "确认作废该单据吗？"
                title: multiLang && multiLang.get('2011-0009'),
                content: multiLang && multiLang.get('2011-0010')
            },
            [pageButton.billEnable] : {
                // "2011-0011": "重启",
                // "2011-0012": "确认重启该单据吗？"
                title: multiLang && multiLang.get('2011-0011'),
                content: multiLang && multiLang.get('2011-0012')
            },
            [pageButton.billClose] : {
                // "2011-0007": "关闭"
                // "2011-0013": "确认关闭该单据吗？",
                title: multiLang && multiLang.get('2011-0007'),
                content: multiLang && multiLang.get('2011-0013')
            }
        }
        const {table} = this.props;
        let { createSimpleTable} = table;
        let { showUploader,target } = this.state;
        return (
            <div>
                {this.renderErrorCenterState()}
                <BillStyle
                    {...this.props}
                >
                    <BillHead
                        // "201102SQFY-0001": "费用申请单"
                        title = {this.state.Title}
                        refreshButtonEvent={refreshButtonClick.bind(this)}
                    >
                        <ButtonGroup
                            areaId="head"
                            buttonEvent={pageButtonClick.bind(this)}
                            modalConfig={btnModalConfig}
                            sagasButtonVisible={true}
                        />

                        <Form
                            areaId="head"
                            onAfterEvent={afterEvent.bind(this)}
                        />
                    </BillHead>

                    <BillBody>
                        <CardTableGroup
                            excludeTableAreaId={null}
                            totalItemCode="orig_amount"
                            modelSave={pageButtonClick.call(this)['pageSave']}
                            modelDelRowBefore={(scope, moduleId, index) => {
                                this.props.cardTable.delRowsByIndex(moduleId, index)
                            }}
                            onAfterEvent={afterEvent.bind(this)}
                        >
                            <MultiButtonGroup buttonEvent={tableButtonClick.bind(this)} />
                        </CardTableGroup>

                        <div>
                            {showUploader && < NCUploader
                                disableButton={ this.state.uploaderBtnDisable }
                                billId={ this.state.billId }
                                targrt={target}
                                onHide={this.onHideUploader}
                                customize={{'pk_billtypecode':this.props.getUrlParam('tradetype'), "djdl":"ma"}}
                                customInterface={
                                    {
                                        queryLeftTree: "/nccloud/erm/pub/ErmAttachmentTreeNodeQueryAction.do",
                                        queryAttachments: "/nccloud/erm/pub/ErmAttachmentQueryAction.do"
                                    }
                                }
                                placement={'bottom'} />
                            }
                        </div>

                        <div>
                            <ApproveDetail
                                show={this.state.ShowApproveDetail}
                                close={this.closeApprove}
                                billtype={this.state.billtype}
                                billid={this.state.billId}
                            />
                        </div>
                        <LinkQueryJkbxModel
                            show={this.state.showModal}
                            linkData={this.state.linkData}
                            close={() => this.setState({showModal: false})}
                            tradetype={window.presetVar.billtype}
                            openBillId={this.state.billId}
                        {...this.props} />
                        
                    </BillBody>
                </BillStyle>
                <div>
                    <Inspection
                        show={ this.state.showLinkBudget }
                        sourceData = { this.state.sourceData }
                        cancel = { this.cancel.bind(this) }
                        affirm = { this.affirm.bind(this) }
                    />
                </div>
                <div>
                    {/*"201102FYYT-0003": "指派",*/}
                    {this.state.compositedisplay ? <ApprovalTrans
                        title={multiLang && multiLang.get('201102FYYT-0003')}
                        data={this.state.compositedata}
                        display={this.state.compositedisplay}
                        getResult={this.getAssginUser}
                        cancel={this.turnOff.bind(this)}
                     /> : ""}

                </div>

                {/* 联查变更历史 */}
                <LinkChangeHistoryModel
                    show={this.state.showLinkQueryChangeHistory}
                    linkData={this.state.linkChangeHisData}
                    close={() => this.setState({showLinkQueryChangeHistory: false})}
                    tradetype={window.presetVar.tradetype}
                    openBillId={this.state.billId}
                    {...this.props} />
            </div>
        );

    }
}

FYSQBill = createPage({
    mutiLangCode: '2011',
    billinfo:{
        billtype: 'card',  //虽然后台是一主多子数据结构，但是配置成extCard，编辑后请求公式验证会报错。因为会根据实际展现的表体数量来判断是一主多子还是一主一子。
        pagecode: presetVar.pageCode, 
        headcode: presetVar.head.head1,
        bodycode: presetVar.body.body1
    },
    orderOfHotKey: [presetVar.body.body1]
})(FYSQBill);

export default FYSQBill;
